<?php

/**
 * ajax actions.
 *
 * @package    raidpoints
 * @subpackage ajax
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ajaxActions extends sfActions
{
    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executePoints($request)
    {
        $this->forward("ajax", "player");
    }

    public function executeRaids($request)
    {
        $this->forward("ajax", "raid");
    }

    public function executePlayer($request)
    {
        $query = Doctrine::getTable("CachePlayerHistory")
                ->createQuery("phc")
                ->select("cache")
                ->where("playerid=?", $request->getParameter('p'))
                ->andWhere("raidid=?", $request->getParameter('r'));
        $result = $query->execute();
        if ($result->count() == 1)
        {
            if (time() < $result->getFirst()->getExpiry())
                return $this->renderText($result->getFirst()->getCache());
            else
                $result->getFirst()->delete();
        }

        $this->getContext()->getConfiguration()->loadHelpers('Partial');
        $text = "";

        $tabs = null;
        $tabs['items'] = array('tab' => 'item', 'id' => 'tabsAjax-item');
        $tabs['points'] = array('tab' => 'point', 'id' => 'tabsAjax-point');
        $tabs['raids'] = array('tab' => 'raid', 'id' => 'tabsAjax-raid');

        $query = Doctrine::getTable("PlayerTalent")
                ->createQuery('pt')
                ->innerJoin("pt.Talent t")
                ->where("pt.playerid=?", $request->getParameter('p'));
        //$text .= $query->getDql();
        //->andWhere("t.id = pt.talentid");
        $result = $query->execute();

        $talentSpecs = array();
        foreach ($result as $talent)
            $talentSpecs[] = $talent->toArray();
        //print_r($talentSpecs);

        //print_r($talentSpecs);

        $query = Doctrine::getTable("ViewRaidPlayers")
                ->createQuery()
                ->select("*")
                ->where("id=?", $request->getParameter('p'))
                ->andWhere("raidid=?", $request->getParameter('r'));
        $result = $query->execute();
        $playerinfo = null;
        //$text .= "Count: ".$result->count()." DQL: ".$query->getDql();
        if ($result->count() == 1)
        {
            $playerinfo = $result->getFirst();
        }
        else
        {
            $query = Doctrine::getTable("ViewRaidPlayers")
                    ->createQuery()
                    ->where("raidid IS NULL")
                    ->andWhere("id=?", $request->getParameter('p'));
            $result = $query->execute();
            if ($result->count() == 1)
            {
                $playerinfo = $result->getFirst();
            }
        }

        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("reason, dt, itemid, SUM(value) as 'value'")
                ->where("raidid=?", $request->getParameter('r'))
                ->andWhere("playerid=?", $request->getParameter('p'))
                ->andWhere("ttype=?", 'I')
                ->andWhere("NOT value=?", 0)
                //->andWhere("date >= ?", $masterTimeLow)
                //->andWhere("date <= ?", $masterTime)
                ->limit(5)
                ->groupBy("dt")
                ->orderBy("dt desc");
        $result = $query->execute();
        //echo "Count: ".$result->count()." DQL: ".$query->getDql();
        $items = array();
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['reason'] = $history['reason'];
                $array['itemid'] = $history['itemid'];
                $array['isItem'] = false;
                $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                if ($match)
                {
                    $array['isItem'] = true;
                    $array['reason'] = $words[0];
                    if ($array['itemid'] == 0)
                    {
                        $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                        if (isset($item[0][1]))
                            $array['itemid'] = $item[0][1];
                    }
                }
                $array['value'] = $history["'value'"];
                $array['quality'] = "q4";
                $array['dt'] = $history['dt'];
                $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                $items[] = $array;
            }
        }

        $points = array();
        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("reason, dt, itemid, SUM(value) as 'value'")
                ->where("raidid=?", $request->getParameter('r'))
                ->andWhere("playerid=?", $request->getParameter('p'))
                ->andWhere("ttype=?", 'P')
                //->andWhere("NOT value=?", 0)
                //->andWhere("date >= ?", $masterTimeLow)
                //->andWhere("date <= ?", $masterTime)
                ->limit(5)
                ->groupBy("dt")
                ->orderBy("dt desc");
        $result = $query->execute();
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['reason'] = $history['reason'];
                $array['itemid'] = $history['itemid'];
                $array['isItem'] = false;
                $array['dt'] = $history['dt'];
                $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                if ($match)
                {
                    $array['reason'] = $words[0];
                    if ($array['itemid'] == 0)
                    {
                        $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                        if (isset($item[0][1]))
                            $array['itemid'] = $item[0][1];
                    }
                }
                $array['value'] = $history["'value'"];
                $array['quality'] = "q4";
                $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                $points[] = $array;
            }
        }

        $raids = array();
        $query = Doctrine::getTable("HistoryRaid")
                ->createQuery('hr')
                ->select("hr.scheduled_date")
                ->where("h.raidid=?", $request->getParameter('r'))
                //->andWhere("h.playerid=?", $request->getParameter('p'))
                ->limit(5)
                ->innerJoin("hr.ViewGuildHistory h")
                ->groupBy("hr.scheduled_date")
                ->orderBy("hr.scheduled_date desc");
        $result = $query->execute();
        if ($result->count() > 0)
        {
            $query = Doctrine::getTable("HistoryGuild")
                    ->createQuery('hg')
                    ->select('dt, scheduled_date')
                    //->where("raidid=?", $request->getParameter('r'))
                    ->addOrderBy("dt desc");
            $dates = array();
            foreach ($result as $history)
            {
                $dates[] = $history['scheduled_date'];
            }
            foreach ($dates as $date)
            {
                $query->orWhere("raidid=?", $request->getParameter('r'))
                        ->andWhere("scheduled_date=?", $date);
            }
            $guildResult = $query->execute();

            $guildRaids = array();
            foreach ($guildResult as $guild)
            {
                if (!isset($guildRaids[$guild['scheduled_date']]))
                    $guildRaids[$guild['scheduled_date']] = array();
                $guildRaids[$guild['scheduled_date']][$guild['dt']] = array('dt' => $guild['dt']);
            }

            $query = Doctrine::getTable("HistoryGuild")
                    ->createQuery('hg')
                    ->select('hg.dt, h.scheduled_date, h.waitlistflag')
                    //->where("1=1")
                    ->innerJoin("hg.ViewGuildHistory h")
                    ->addOrderBy("h.dt desc");

            foreach ($dates as $date)
            {
                $query->orWhere("h.raidid=?", $request->getParameter('r'))
                        ->andWhere("h.playerid=?", $request->getParameter('p'))
                        ->andWhere("hg.scheduled_date=?", $date);
            }
            $playerResult = $query->execute();

            $playerRaids = array();
            foreach ($playerResult as $player)
            {
                if (!isset($playerRaids[$player['ViewGuildHistory']['scheduled_date']]))
                    $playerRaids[$player['ViewGuildHistory']['scheduled_date']] = array();
                $playerRaids[$player['ViewGuildHistory']['scheduled_date']][$player['dt']] = array('dt' => $player['dt'], 'waitlist' => $player['ViewGuildHistory']['waitlistflag']);
            }

            foreach ($guildRaids as $s => $guild)
            {
                $array = array();
                $array['block'] = array();
                $i = 0;
                $notMissed = false;
                $dtStart = 0;
                foreach ($guild as $dt => $r)
                {
                    if ($dtStart == 0 || strtotime($dt) < strtotime($dtStart))
                        $dtStart = $dt;
                    if (isset($playerRaids[$s][$dt]))
                    {
                        if ($playerRaids[$s][$dt]['waitlist'] == 1)
                        {
                            $array['block'][] = 'waitlist';
                            $notMissed = true;
                        }
                        else
                        {
                            $array['block'][] = 'raid';
                            $notMissed = true;
                        }
                    }
                    else
                    {
                        $array['block'][] = 'blank';
                        if ($i == 0)
                            $array['state'] = 'Late';
                        elseif ($i == count($guild[$dt])-1)
                            $array['state'] = (isset($array['state'])?($array['state'].' / '):'').'Left Early';
                    }
                }
                $array['date'] = date('m/d/y', strtotime($dtStart." GMT"));
                ;
                if (!$notMissed)
                    $array['state'] = "Missing";
                else
                    $array['state'] = "Attended";
                $raids[] = $array;
            }
        }

//         $this->name = 'player';
//         $this->playerinfo = $playerinfo;
//         $this->items = $items;
//         $this->points = $points;
//         $this->raids = $raids;
//         $this->talentSpecs = $talentSpecs;
//         return;

        $tabs['items']['value'] = $items;
        $tabs['points']['value'] = $points;
        $tabs['raids']['value'] = $raids;
        $cacheText = get_partial('ajax/player', array(
                'name' => 'points',
                'playerinfo' => $playerinfo,
                'tabs' => $tabs,
                'talentSpecs' => $talentSpecs,
        ));

        $cache = new CachePlayerHistory();
        $cache->setPlayerid($request->getParameter('p'));
        $cache->setRaidid($request->getParameter('r'));
        $cache->setCache($cacheText);
        $cache->setExpiry(time()+(60*60*24));
        $cache->save();

        return $this->renderText($cacheText);
    }

    public function executeRaid($request)
    {
        $query = Doctrine::getTable("CacheRaidHistory")
                ->createQuery("rhc")
                ->select("cache")
                ->where("scheduled_date=?", $request->getParameter('p'))
                ->andWhere("raidid=?", $request->getParameter('r'));
        $result = $query->execute();
        if ($result->count() == 1)
        {
            if (time() < $result->getFirst()->getExpiry())
                return $this->renderText($result->getFirst()->getCache());
            else
                $result->getFirst()->delete();
        }

        $this->getContext()->getConfiguration()->loadHelpers('Partial');
        $text = "";

        $tabs = null;
        $tabs['players'] = array('tab' => 'player', 'id' => 'tabsAjax-player');
        $tabs['items'] = array('tab' => 'item_player', 'id' => 'tabsAjax-itemplayer');
        $tabs['points'] = array('tab' => 'point', 'id' => 'tabsAjax-point');

        $query = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value) as 'value', raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc")
                ->orWhere("h.raidid=?", $request->getParameter('r'))
                ->andWhere("h.scheduled_date=?", $request->getParameter('p'))
                ->andWhere("h.value > 0");

        $query2 = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value) as 'value', raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc")
                ->orWhere("h.raidid=?", $request->getParameter('r'))
                ->andWhere("h.scheduled_date=?", $request->getParameter('p'))
                ->andWhere("h.value < 0");

        $gainResult = $query->execute();
        $lossResult = $query2->execute();

        $loss = 0;
        if ($lossResult->count() > 0)
        {
            $loss = $lossResult->getFirst();
            $loss = $loss["'value'"];
        }

        $gain = 0;
        if ($gainResult->count() > 0)
        {
            $gain = $gainResult->getFirst();
            $gain = $gain["'value'"];
        }

        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("reason, dt, itemid, SUM(value) as 'value'")
                ->where("raidid=?", $request->getParameter('r'))
                ->andWhere("scheduled_date=?", $request->getParameter('p'))
                ->andWhere("ttype=?", 'I')
                ->andWhere("NOT value=?", 0)
                //->limit(5)
                ->groupBy("dt")
                ->orderBy("dt desc");
        $result = $query->execute();
        //echo "Count: ".$result->count()." DQL: ".$query->getDql();
        $items = array();
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['reason'] = $history['reason'];
                $array['itemid'] = $history['itemid'];
                $array['isItem'] = false;
                $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                if ($match)
                {
                    $array['isItem'] = true;
                    $array['reason'] = $words[0];
                    if ($array['itemid'] == 0)
                    {
                        $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                        if (isset($item[0][1]))
                            $array['itemid'] = $item[0][1];
                    }
                }
                $array['value'] = $history["'value'"];
                $array['player'] = $history['name'];
                $array['quality'] = "q4";
                $array['dt'] = $history['dt'];
                $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                $items[] = $array;
            }
        }

        $points = array();
        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("reason, dt, itemid, SUM(value) as 'value'")
                ->where("raidid=?", $request->getParameter('r'))
                ->andWhere("scheduled_date=?", $request->getParameter('p'))
                ->andWhere("ttype=?", 'P')
                //->andWhere("NOT value=?", 0)
                //->andWhere("date >= ?", $masterTimeLow)
                //->andWhere("date <= ?", $masterTime)
                //->limit(5)
                ->groupBy("dt")
                ->orderBy("dt desc");
        $result = $query->execute();
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['reason'] = $history['reason'];
                $array['itemid'] = $history['itemid'];
                $array['isItem'] = false;
                $array['dt'] = $history['dt'];
                $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                if ($match)
                {
                    $array['reason'] = $words[0];
                    if ($array['itemid'] == 0)
                    {
                        $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                        if (isset($item[0][1]))
                            $array['itemid'] = $item[0][1];
                    }
                }
                $array['value'] = $history["'value'"];
                $array['quality'] = "q4";
                $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                $array['player'] = $history['name'];
                $points[] = $array;
            }
        }

        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->distinct()
                ->select("name, dt, reasonid, value, waitlistflag")
                ->where("scheduled_date=?", $request->getParameter('p'))
                ->orderBy("name asc");
        $result = $query->execute();

        $players = null;
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['isItem'] = false;
                $array['player'] = ucwords($history['name']);
                $array['dt'] = $history["dt"];
                $array['value'] = $history["value"];
                $array['waitlist'] = $history["waitlistflag"];
                $array['quality'] = "q4";
                $players[$history['name']][$history['dt']] = $array;
            }
        }

        $query = Doctrine::getTable("HistoryGuild")
                ->createQuery('hg')
                ->select('dt, scheduled_date')
                //->where("raidid=?", $request->getParameter('r'))
                ->addOrderBy("dt desc")
                ->andWhere("raidid=?", $request->getParameter('r'))
                ->andWhere("scheduled_date=?", $request->getParameter('p'));
        $guildResult = $query->execute();

        $guildRaids = array();
        foreach ($guildResult as $guild)
        {
            if (!isset($guildRaids[$guild['scheduled_date']]))
                $guildRaids[$guild['scheduled_date']] = array();
            $guildRaids[$guild['scheduled_date']][$guild['dt']] = array('dt' => $guild['dt']);
        }

        $pArray = array();
        foreach ($players as $p => $data)
        {
            $raids = null;
            foreach ($guildRaids as $s => $guild)
            {
                $array = array();
                $array['block'] = array();
                $i = 0;
                $notMissed = false;
                $dtStart = 0;
                foreach ($guild as $dt => $r)
                {
                    if ($dtStart == 0 || strtotime($dt) < strtotime($dtStart))
                        $dtStart = $dt;
                    if (isset($data[$dt]))
                    {
                        if ($data[$dt]['waitlist'] == 1)
                        {
                            $array['block'][] = 'waitlist';
                            $notMissed = true;
                        }
                        else
                        {
                            $array['block'][] = 'raid';
                            $notMissed = true;
                        }
                    }
                    else
                    {
                        $array['block'][] = 'blank';
                        if ($i == 0)
                            $array['state'] = 'Late';
                        elseif ($i == count($guild[$dt])-1)
                            $array['state'] = (isset($array['state'])?($array['state'].' / '):'').'Left Early';
                    }
                }
                $array['date'] = date('m/d/y', strtotime($dtStart." GMT"));
                $array['player'] = $p;
                ;
                if (!$notMissed)
                    $array['state'] = "Missing";
                else
                    $array['state'] = "Attended";
                $raids[] = $array;
            }
            $pArray[$p] = $raids[0];
        }
        $players = $pArray;

        $query = Doctrine::getTable("Raid")
                ->createQuery('r')
                ->where("id=?", $request->getParameter('r'));
        $raidData = $query->execute();

        $tabs['items']['value'] = $items;
        $tabs['points']['value'] = $points;
        $tabs['players']['value'] = $players;
        $cacheText = get_partial('ajax/raid', array(
                'name' => 'raids',
                'gain' => $gain,
                'loss' => $loss,
                'points' => $gain+$loss,
                'date' => $request->getParameter('p'),
                'tabs' => $tabs,
                'raid' => $raidData->getFirst->toArray(),
        ));

        $cache = new CacheRaidHistory();
        $cache->setScheduledDate($request->getParameter('p'));
        $cache->setRaidid($request->getParameter('r'));
        $cache->setCache($cacheText);
        $cache->setExpiry(time()+(60*60*24));
        $cache->save();

        return $this->renderText($cacheText);
    }

    public function executeItem($request)
    {
        $this->getContext()->getConfiguration()->loadHelpers('Partial');

        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("reason, itemid, name, dt, SUM(value) as 'value'")
                ->where("reason like ?", "%".$request->getParameter('s')."%")
                ->andWhere("ttype=?", 'I')
                ->groupBy("dt")
                ->orderBy("dt desc");
        $result = $query->execute();

        $items = null;
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['isItem'] = false;
                $array['itemid'] = $history['itemid'];
                if ($array['itemid'] == 0)
                {
                    $match = preg_match_all('/[^:]+/i', $history['reason'], $item);
                    if (isset($item[0][1]))
                        $array['itemid'] = $item[0][1];
                }
                $array['player'] = ucwords($history['name']);
                $array['value'] = $history["'value'"];
                $array['quality'] = "q4";
                $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));

                if ( $array['itemid'] == intval(substr($request->getParameter('i'), strpos($request->getParameter('i'), "=")+1)) || intval(substr($request->getParameter('i'), strpos($request->getParameter('i'), "=")+1)) == 0)
                    $items[] = $array;
            }
        }
        return $this->renderText(get_partial('ajax/dialog_item', array(
                'items' => $items,
        )));
    }

    public function executeHistory($request)
    {
        $this->getContext()->getConfiguration()->loadHelpers('Partial');
        $query = Doctrine::getTable("ViewHistory")
                ->createQuery()
                ->select("name, dt, reasonid, value, waitlistflag")
                ->where("dt=?", $request->getParameter('s'));
        $result = $query->execute();

        $items = null;
        if ($result->count() > 0)
        {
            foreach ($result as $history)
            {
                $array = array();
                $array['isItem'] = false;
                $array['player'] = ucwords($history['name']);
                $array['dt'] = $history["dt"];
                $array['value'] = $history["value"];
                $array['waitlist'] = $history["waitlistflag"];
                $array['quality'] = "q4";
                $items[] = $array;
            }
        }
        return $this->renderText(get_partial('ajax/dialog_history', array(
                'items' => $items,
        )));
    }
}
